<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系统单号" prop="sid">
        <el-input
          v-model="queryParams.sid"
          placeholder="请输入系统单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('sid')"/>
        </el-input>
      </el-form-item>
      <el-form-item label="平台单号" prop="tid">
        <el-input
          v-model="queryParams.tid"
          placeholder="请输入平台单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('tid')"/>
        </el-input>
      </el-form-item>
      <el-form-item label="快递单号" prop="outSid">
        <el-input
          v-model="queryParams.outSid"
          placeholder="请输入快递单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('outSid')"/>
        </el-input>
      </el-form-item>
      <el-form-item label="内部单号" prop="shortId">
        <el-input
          v-model="queryParams.shortId"
          placeholder="请输入内部单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-edit-outline" @click="handleOpenDialog('shortId')"/>
        </el-input>
      </el-form-item>
      <el-form-item label="四合一" prop="conditions">
        <el-input
          v-model="queryParams.conditions"
          placeholder="请输入系统单号/内部单号/平台单号/快递单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="快递公司" prop="expressCode">
        <el-select v-model="queryParams.expressCode" placeholder="请输入快递公司" clearable style="width: 240px" @keyup.enter.native="handleQuery">
          <el-option label="顺丰速运" value="SF" />
          <el-option label="中通快递" value="ZTO" />
          <el-option label="申通快递" value="STO" />
          <el-option label="极兔速递" value="JTSD" />
          <el-option label="圆通速递" value="YTO" />
          <el-option label="未设定快递公司" value="NOEXPRESS" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="created">
        <el-date-picker clearable style="width: 240px"
                        value-format="timestamp"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        @keyup.enter.native="handleQuery"
                        v-model="createdTimeRange"/>

      </el-form-item>
      <el-form-item label="付款时间" prop="payTime">
        <el-date-picker clearable style="width: 240px"
                        value-format="timestamp"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        @keyup.enter.native="handleQuery"
                        v-model="payTimeRange"/>
      </el-form-item>
      <el-form-item label="处理时间" prop="accessTime">
        <el-date-picker clearable style="width: 240px"
                        value-format="timestamp"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        @keyup.enter.native="handleQuery"
                        v-model="accessTimeRange"/>
      </el-form-item>
      <el-form-item label="分配时间" prop="assignTime">
        <el-date-picker clearable style="width: 240px"
                        value-format="timestamp"
                        type="datetimerange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        @keyup.enter.native="handleQuery"
                        v-model="assignTimeRange"/>
      </el-form-item>
      <el-form-item label="系统状态" prop="sysStatus">
        <el-select v-model="queryParams.sysStatus" placeholder="请选择系统状态" clearable style="width: 240px" @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in dict.type.sys_orders_status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" @input="handleUserList" placeholder="请选择部门" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="设计师" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择设计师" filterable clearable style="width: 240px" @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in filteredUserOptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="已付金额" prop="payAmount">
        <input-number-range :precision="2" v-model="payAmountRange" style="width: 240px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload"
          @click="handleUploadDialog"
          v-hasPermi="['business:ordersStatus:match']"
        >单号上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-view"
          @click="handleViewCustomerLogs"
          v-hasPermi="['business:customerLogs:viewCustomerLogs']"
        >查看日志</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + (divHeight - 50) + 'px'">
      <el-alert
        title="说明"
        type="error"
        description="页面数据是处理状态为设计退回的"
        show-icon
        :closable="false">
      </el-alert>
      <el-table ref="queryOrderTable" v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" @expand-change="expandChange" @row-click="(row, column, event) => handleRowClick(row, event)" :expand-row-keys="expandedKeys" row-key="sid">
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-table ref="details" :data="scope.row.children" :height="scope.row.height" v-loading="detailsLoading" :show-header="false" :span-method="objectSpanMethod" :key="'details_' + scope.row.sid" >
              <el-table-column width="250">
                <template v-slot="scope">
                  系统单号: {{scope.row.detailSid}} <svg-icon v-if="scope.row.isMergeMain === 1" class-name="main" icon-class="main" />
                  <br/>
                  平台单号：{{scope.row.tid}}
                </template>
              </el-table-column>
              <el-table-column width="1200">
                <template v-slot="scope">
                  <div style="display: flex; align-items: center;">
                    <div style="flex: 0 0 auto; display: flex; align-items: center; justify-content: center;">
                      <image-preview :src="scope.row.picPath" style="width: 158px; height: 155px;" />
                    </div>
                    <div style="flex: 1; margin-left: 16px;">
                      标题： <span :class="{'gift-text': scope.row.isGift === 'Y'}">{{ scope.row.isGift === 'Y' ? '[平台赠品]' : '' }}</span> {{ scope.row.title }}
                      <br/>
                      数量：{{scope.row.num}}
                      <br/>
                      SK：{{scope.row.outerSkuId}}
                      <br/>
                      规格属性：{{scope.row.sysSkuPropertiesName}}
                      <div>
                        <div style="float: left;">
                          系统状态：
                        </div>
                        <dict-tag :options="dict.type.sys_orders_status" :value="scope.row.sysStatus" style="float:left;"/>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="sellerMemo" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="50">
          <template v-slot="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" align="center" prop="shopName" />
        <el-table-column label="系统单号" align="center" prop="sid" width="160">
          <template v-slot="scope">
            {{ scope.row.sid }}
            <el-link :underline="false" type="primary" v-clipboard:copy="String(scope.row.sid)" v-clipboard:success="clipboardSuccess" style="margin-left: 5px;">
              <el-icon class="el-icon-copy-document"  style="margin-left: 5px; cursor: pointer;" />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="平台单号" align="center" prop="tid" width="180">
          <template v-slot="scope">
            {{ scope.row.tid }}
            <el-link :underline="false" type="primary" v-clipboard:copy="scope.row.tid" v-clipboard:success="clipboardSuccess" style="margin-left: 5px;">
              <el-icon class="el-icon-copy-document"  style="margin-left: 5px; cursor: pointer;" />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="内部单号" align="center" prop="shortId" width="120">
          <template v-slot="scope">
            {{ scope.row.shortId }}
            <el-link :underline="false" type="primary" @click.stop="handleViewLog($event, scope.$index, scope.row.sid, 'main')" style="margin-left: 5px;">
              <svg-icon icon-class="log" />
              <el-popover
                :ref="`logPopover_main_${scope.row.sid}_${scope.$index}`"
                placement="right"
                trigger="click"
                v-if="logData && logData.length > 0">
                <ul style="max-height: 300px;overflow-y: auto;padding: 5px 10px;font-size: 12px">
                  <li v-for="(item, index) in logData" :key="index" style="border-bottom: 1px solid #eaeaea;display: flex;width: 700px;line-height: 24px">
                    <span style="width: 130px">{{$parseTime(item.created, '{y}-{m}-{d} {h}:{i}:{s}')}}</span>
                    <span style="flex: 1;text-align: left;word-break: break-all;">{{ item.content }}</span>
                    <span style="width: 80px"><user-tag :value="item.userId" type="userId"/></span>
                  </li>
                </ul>
                <span slot="reference"></span>
              </el-popover>
            </el-link>
            <el-link :underline="false" type="primary" v-clipboard:copy="scope.row.shortId" v-clipboard:success="clipboardSuccess" style="margin-left: 5px;">
              <el-icon class="el-icon-copy-document"  style="margin-left: 5px; cursor: pointer;" />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="itemNum" width="110">
          <template v-slot="scope">
            <span style="font-size: 15px">{{scope.row.itemNum}}</span> ({{scope.row.itemKindNum}}种)
          </template>
        </el-table-column>
        <el-table-column label="已付金额" align="center" prop="payAmount" />
        <el-table-column label="快递公司" align="center" prop="expressCompanyName" width="110">
          <template v-slot="scope">
            {{ scope.row.expressCompanyName }}
            <el-link v-if="scope.row.expressCompanyName" :underline="false" type="primary" v-clipboard:copy="scope.row.expressCompanyName" v-clipboard:success="clipboardSuccess" style="margin-left: 5px;">
              <el-icon class="el-icon-copy-document"  style="margin-left: 5px; cursor: pointer;" />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="运单号" align="center" prop="outSid" width="130">
          <template v-slot="scope">
            {{ scope.row.outSid }}
            <el-link v-if="scope.row.outSid" :underline="false" type="primary" v-clipboard:copy="scope.row.outSid" v-clipboard:success="clipboardSuccess" style="margin-left: 5px;">
              <el-icon class="el-icon-copy-document"  style="margin-left: 5px; cursor: pointer;" />
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="卖家备注" align="center" prop="mergeList">
          <template v-slot="scope">
            <div v-if="scope.row.mergeList && scope.row.mergeList.length > 0">
              <template v-for="(item, index) in scope.row.mergeList">
                <div v-if="item && item.sellerMemo" :key="index" style="display: flex; align-items: center; justify-content: center;">
                  <el-tooltip
                    effect="dark"
                    :content="item.sellerMemo"
                    placement="top"
                    popper-class="custom-tooltip"
                  >
                    <el-icon class="el-icon-s-comment" style="font-size: 20px;color: #189f15" />
                  </el-tooltip>
                  <el-link :underline="false" type="primary" v-clipboard:copy="item.sellerMemo" v-clipboard:success="clipboardSuccess" style="margin-left: 10px;" >
                    <el-icon class="el-icon-copy-document"  />
                  </el-link>
                </div>
              </template>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center" prop="created" width="140">
          <template v-slot="scope">
            {{$parseTime(scope.row.created, '{y}-{m}-{d} {h}:{i}:{s}')}}
          </template>
        </el-table-column>
        <el-table-column label="付款时间" align="center" prop="payTime" width="140">
          <template v-slot="scope">
            {{$parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}')}}
          </template>
        </el-table-column>
        <el-table-column label="系统状态" align="center" prop="sysStatus" >
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_orders_status" :value="scope.row.sysStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" align="center" prop="orderStatus" width="110">
          <template v-slot="scope">
            <dict-tag :options="dict.type.self_orders_status" :value="scope.row.orderStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center" prop="accessTime" width="140">
          <template v-slot="scope">
            {{$parseTime(scope.row.accessTime, '{y}-{m}-{d} {h}:{i}:{s}')}}
          </template>
        </el-table-column>
        <el-table-column label="接单人" align="center" prop="customer" >
          <template v-slot="scope">
            <user-tag :value="scope.row.customer" type="userId"/>
          </template>
        </el-table-column>
        <el-table-column label="设计师" align="center" prop="userId" >
          <template v-slot="scope">
            <user-tag :value="scope.row.userId" type="userId"/>
          </template>
        </el-table-column>
        <el-table-column label="分配时间" align="center" prop="assignTime" width="140">
          <template v-slot="scope">
            {{$parseTime(scope.row.assignTime, '{y}-{m}-{d} {h}:{i}:{s}')}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button
              type="text"
              icon="el-icon-folder-checked"
              v-if="scope.row.orderStatus === 'MANUAL_RETURNED'"
              @click="handleReceive(scope.row)"
              v-hasPermi="['business:ordersStatus:receive']"
            >退回接收</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :pageRefs="this.$refs"
        :total="total"
        :pageSizes= [50,100,150,200]
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog title="批量添加" :visible.sync="open" width="500px" append-to-body>
      <el-input type="textarea" :rows="10" placeholder="请输入系统单号/平台单号/快递单号/内部单号，多个用英文逗号隔开" v-model="dialogInput" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchConfirm">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="单号上传" :visible.sync="uploadVisible" width="500px" append-to-body>
      部门类型：
      <el-radio-group v-model="buType">
        <el-radio :label="0">3C事业部</el-radio>
        <el-radio :label="1">海报事业部</el-radio>
      </el-radio-group>
      <br/>
      单号类型：
      <el-radio-group v-model="orderType">
        <el-radio :label="0">平台单号</el-radio>
        <el-radio :label="1">系统单号</el-radio>
      </el-radio-group>
      <el-input type="textarea" :rows="10" placeholder="请输入平台单号/系统单号，多个用英文逗号隔开" v-model="tidSidInput" style="margin-top: 5px;"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleMatch" :disabled="!tidSidInput">匹 配</el-button>
        <el-button @click="uploadVisible=false;orderType=0;">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 客服整理日志 -->
    <el-dialog title="整理日志" :visible.sync="viewCustomerLogsVisible" width="800px" append-to-body>
      <el-form :model="queryCustomerLogsParams" ref="queryCustomerLogsForm" :inline="true">
        <el-form-item label="上传时间" prop="createTime">
          <el-date-picker clearable style="width: 240px"
                          type="datetimerange"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          range-separator="-"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          @keyup.enter.native="handleCustomerLogsQuery"
                          v-model="createTimeRange"/>
        </el-form-item>
        <el-form-item label="日志内容" prop="content">
          <el-input
            v-model="queryCustomerLogsParams.content"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleCustomerLogsQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleCustomerLogsQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetCustomerLogsQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row>
        <div :style="'height: calc(45vh - 120px)'">
          <el-table ref="table" :data="customerLogsList" height="94%">
            <el-table-column label="上传时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ $parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="上传人" align="center" prop="userId" width="100">
              <template slot-scope="scope">
                <user-tag :value="scope.row.userId" type="userId"/>
              </template>
            </el-table-column>
            <el-table-column label="日志内容" align="center" prop="content" show-overflow-tooltip>
              <template slot-scope="scope">
                <div style="display: flex; align-items: center;">
                  <el-link :underline="false" type="primary" v-clipboard:copy="scope.row.content" v-clipboard:success="clipboardSuccess" style="margin-right: 5px;">
                    <el-icon class="el-icon-copy-document"/>
                  </el-link>
                  <span>{{ scope.row.content }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            style="bottom: -5px"
            v-show="customerTotal>0"
            :total="customerTotal"
            :page.sync="queryCustomerLogsParams.pageNum"
            :limit.sync="queryCustomerLogsParams.pageSize"
            @pagination="getCustomerLogsList"
          />
        </div>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewCustomerLogsVisible = false">关 闭</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { getListByMainSid, getMyTasks} from "@/api/business/ordersMain";
import {listLog} from "@/api/business/ordersLog";
import { checkTidIsUnique, getOrderStatusInfo, updateOrderStatus } from "@/api/business/ordersStatus"
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptTreeSelect, getNormalUserInfo} from "@/api/system/user";
import InputNumberRange from "@/components/InputNumberRange/index.vue";
import { addCustomerLogs, listCustomerLogs } from "@/api/business/customerLogs"

export default {
  name: "OrderCustomer",
  mixins: [ResizeMixin],
  dicts: ['sys_orders_status', 'self_orders_status'],
  components: {InputNumberRange, Treeselect },
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 明细遮罩层
      detailsLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务-订单主表格数据
      orderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        tid: null,
        shortId: null,
        shopName: null,
        itemNum: null,
        itemKindNum: null,
        payAmount: null,
        sysStatus: null,
        expressCompanyName: null,
        expressCode: null,
        outSid: null,
        tags: null,
        created: null,
        payTime: null,
        updTime: null,
        accessTime: null,
        conditions: null,
        orderStatus: 'MANUAL_RETURNED',
      },
      // 下单时间查询
      createdTimeRange: [],
      // 付款时间查询
      payTimeRange: [],
      // 处理时间
      accessTimeRange: [],
      // 分配时间
      assignTimeRange: [],
      // 单元格合并
      rowSpanArr: [],
      // 日志弹出框
      logVisible: false,
      // 日志内容
      logData: [],
      // 存储当前展开的行的 sid
      expandedKeys: [],
      // 使用Map来存储每个展开行的合并配置
      rowSpanMap: new Map(),
      // 批量添加弹出框
      open: false,
      // 存储 dialog 中输入的内容
      dialogInput: null,
      // 当前点击的 input 类型（sid、tid、outSid、shortId）
      currentInputType: '',
      // 单号上传
      uploadVisible: false,
      // 存储平台单号/系统单号
      tidSidInput: null,
      // 单号类型
      orderType: 0,
      // 部门树选项
      deptOptions: [],
      // 用户选项
      userOptions: [],
      // 过滤后的用户数据
      filteredUserOptions: [],
      // 已付金额区间
      payAmountRange: [],
      // 事业部类型
      buType: 0,
      // 客服整理日志弹框
      viewCustomerLogsVisible: false,
      // 日志列表
      customerLogsList: [],
      queryCustomerLogsParams: {
        pageNum: 1,
        pageSize: 10,
      },
      customerTotal: 0,
      createTimeRange: [],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getUserList();
  },
  methods: {
    /** 查询业务-订单主列表 */
    getList() {
      this.loading = true;
      let searchParams = this.$addDateRange(this.queryParams, this.createdTimeRange, 'Created');
      searchParams = this.$addDateRange(this.queryParams, this.payTimeRange, 'PayTime');
      searchParams = this.$addDateRange(this.queryParams, this.accessTimeRange, 'AccessTime');
      searchParams = this.$addDateRange(this.queryParams, this.assignTimeRange, 'AssignTime');
      searchParams = this.$addDateRange(this.queryParams, this.payAmountRange, 'PayAmount');
      getMyTasks(searchParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createdTimeRange = [];
      this.payTimeRange = [];
      this.accessTimeRange = [];
      this.assignTimeRange = [];
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sid)
      this.selected = !this.ids.length
    },
    /** 展开行 */
    expandChange(row,expandedRows){
      const _this = this
      if (expandedRows.length) {
        this.detailsLoading = true;
        getListByMainSid(row.sid).then(response => {
          this.detailsLoading = false;
          const processedData = this.handleTableData(response.rows, row.sid); // 传入row.sid作为key
          row.children = processedData.rows;
          row.height = (response.rows.length*168) + 'px'
          this.$nextTick(() => {
            _this.$refs["queryOrderTable"].doLayout();
            if (_this.$refs["details"]) _this.$refs["details"].doLayout();
          })
        });
      }

    },
    /** 合并单元格*/
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 找到当前行的父级sid
      const parentRow = this.findParentRow(row);
      if (!parentRow) return { rowspan: 1, colspan: 1 };

      // 从Map中获取对应的合并配置
      const rowSpanArr = this.rowSpanMap.get(parentRow.sid);
      if (!rowSpanArr) return { rowspan: 1, colspan: 1 };

      if (columnIndex === 0 || columnIndex === 2) {
        return {
          rowspan: rowSpanArr[rowIndex],
          colspan: 1
        };
      }
      return { rowspan: 1, colspan: 1 };
    },
    // 辅助方法：找到当前行的父级行
    findParentRow(row) {
      for (const parent of this.orderList) {
        if (parent.children && parent.children.includes(row)) {
          return parent;
        }
      }
      return null;
    },
    /** 获取相同名称的个数 */
    handleTableData(tableData, key){
      let rowSpanArr = [], position = 0;
      const rows = [...tableData]; // 创建副本避免修改原数据
      for (let [index, item] of rows.entries()) {
        if (index === 0) {
          rowSpanArr.push(1);
          position = 0;
        } else {
          if (item.detailSid === rows[index - 1].detailSid && rows[index - 1].isMergeMain === 1) {
            rowSpanArr[position] += 1;
            rowSpanArr.push(0);
          } else {
            rowSpanArr.push(1);
            position = index;
          }
        }
      }
      // 使用Map存储每个展开行的合并配置
      this.rowSpanMap.set(key, rowSpanArr);
      return {
        rows,
        rowSpanArr
      };
    },
    /** 查看日志 */
    handleViewLog(event, index, logSid, source = 'main'){
      event?.stopPropagation(); // 阻止冒泡，避免触发表格行点击

      // 先关闭之前打开的弹窗（如果有）
      if (this.currentOpenLogRef) {
        this.$refs[this.currentOpenLogRef]?.doClose();
      }
      // 记录当前弹窗的 ref
      const popoverRef = `logPopover_${source}_${logSid}_${index}`;
      this.currentOpenLogRef = popoverRef;

      // 显示当前弹窗
      listLog({ logSid }).then(res => {
        if (res.total > 0) {
          this.logData = res.rows
          this.$nextTick(() => {
            this.$refs[popoverRef]?.doShow();
          });
        }
      });
    },
    /** 点击展开行 */
    handleRowClick(row, event){
      if (event.target.closest('.el-link') || event.target.closest('.el-button')) {
        return;
      }
      const index = this.expandedKeys.indexOf(row.sid);
      if (index > -1) {
        // 如果已展开，则关闭
        this.expandedKeys.splice(index, 1);
      } else {
        // 如果未展开，则展开
        this.expandedKeys.push(row.sid);
        this.expandChange(row, [row]);
      }
    },
    /** 单号上传按钮操作 */
    handleUploadDialog(){
      this.uploadVisible = true;
      this.tidSidInput = null;
    },
    /** 刷新方法 */
    refresh() {
      this.getList();
    },
    /** 打开弹出框 */
    handleOpenDialog(type){
      this.currentInputType = type; // 记录当前 input 类型
      // 将当前 input 的内容赋值给 dialogInput
      switch (type) {
        case 'sid':
          this.dialogInput = this.queryParams.sid || '';
          break;
        case 'tid':
          this.dialogInput = this.queryParams.tid || '';
          break;
        case 'outSid':
          this.dialogInput = this.queryParams.outSid || '';
          break;
        case 'shortId':
          this.dialogInput = this.queryParams.shortId || '';
          break;
        default:
          this.dialogInput = '';
          break;
      }
      this.open = true; // 打开 dialog
    },
    /** 弹出框确认 */
    handleBatchConfirm() {
      if (this.dialogInput) {
        // 根据当前 input 类型，将 dialog 中的内容赋值给对应的 queryParams 字段
        switch (this.currentInputType) {
          case 'sid':
            this.queryParams.sid = this.dialogInput;
            break;
          case 'tid':
            this.queryParams.tid = this.dialogInput;
            break;
          case 'outSid':
            this.queryParams.outSid = this.dialogInput;
            break;
          case 'shortId':
            this.queryParams.shortId = this.dialogInput;
            break;
          default:
            break;
        }
        this.open = false; // 关闭 dialog
      }
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    /** 批量匹配 */
    handleMatch() {
      // 单号去重
      const tidList = [...new Set(this.tidSidInput.split(',').map(item => item.trim()))];

      // 初始化统计信息
      const stats = {
        total: tidList.length,
        uploadList: tidList, // 记录原始单号列表
        success: 0,
        failed: 0,
        // 使用对象存储每个单号的所有问题
        problemMap: new Map(),
        // 问题类型常量
        PROBLEM_TYPES: {
          DUPLICATE: '单号重复',
          SELF_STATUS: '自建状态不符',
          SYS_STATUS: '系统状态不符',
          NOT_EXIST: '单号不存在',
          UPDATE_FAILED: '更新失败'
        }
      };

      // 平台单号处理
      if (this.orderType === 0) {
        const tidOrders = tidList.map(tid => ({ tid }));

        checkTidIsUnique(tidOrders, 'MANUAL').then(res => {
          // 记录重复单号
          const duplicates = res.data || [];
          duplicates.forEach(tid => {
            this.recordProblem(stats, tid, stats.PROBLEM_TYPES.DUPLICATE);
            stats.failed++; // 重复单号计入失败
          });

          // 过滤掉重复单号（非重复的才进行后续处理）
          const uniqueTidOrders = tidOrders.filter(
            order => !duplicates.includes(order.tid)
          );

          if (uniqueTidOrders.length > 0) {
            this.submitOrders(uniqueTidOrders, 0, stats);
          } else {
            this.finalizeResult(stats);
          }
        }).catch(error => {
          this.$modal.msgError('检查重复单号失败');
          console.error(error);
        });
      }
      // 系统单号处理
      else {
        const sidOrders = tidList.map(sid => ({ sid }));
        this.submitOrders(sidOrders, 1, stats);
      }
    },
    /** 记录单号问题 */
    recordProblem(stats, id, problemType, status) {
      if (!stats.problemMap.has(id)) {
        stats.problemMap.set(id, []);
      }

      let problemDesc = problemType;
      if (status) {
        problemDesc += `【${status}】`;
      }

      // 避免重复记录相同问题
      if (!stats.problemMap.get(id).includes(problemDesc)) {
        stats.problemMap.get(id).push(problemDesc);
      }
    },
    /** 批量提交单号 */
    async submitOrders(orders, orderType, stats) {
      const user = this.$store.state.user;

      // 获取订单状态信息
      const res = await getOrderStatusInfo(orders).catch(error => {
        // 接口调用失败处理
        orders.forEach(order => {
          const id = orderType === 0 ? order.tid : order.sid;
          this.recordProblem(stats, id, '接口调用失败');
        });
        stats.failed = orders.length; // 所有订单计入失败
        this.finalizeResult(stats);
        return { data: null };
      });

      if (!res || !res.data) return;

      const inputIds = orders.map(order => orderType === 0 ? order.tid : order.sid);
      const matchedItems = res.data;

      // 检查不存在的单号
      const matchedIds = matchedItems.map(item => orderType === 0 ? item.tid : item.sid);
      const notExistIds = inputIds.filter(id => !matchedIds.includes(id));

      notExistIds.forEach(id => {
        this.recordProblem(stats, id, stats.PROBLEM_TYPES.NOT_EXIST);
      });
      stats.failed += notExistIds.length;

      // 处理存在的单号
      const validItemsToUpdate = [];

      for (const item of matchedItems) {
        const currentId = orderType === 0 ? item.tid : item.sid;
        let hasProblem = false;

        // 检查系统状态
        if (['CLOSED', 'CANCEL'].includes(item.sysStatus)) {
          const statusText = item.sysStatus === 'CLOSED' ? '交易关闭' : '交易取消';
          this.recordProblem(stats, currentId, stats.PROBLEM_TYPES.SYS_STATUS, statusText);
          hasProblem = true;
        }

        // 检查自建状态
        if (item.orderStatus !== 'MANUAL') {
          const statusName = this.dict.type.self_orders_status.find(
            d => d.value === item.orderStatus
          )?.label || item.orderStatus;
          this.recordProblem(stats, currentId, stats.PROBLEM_TYPES.SELF_STATUS, statusName);
          hasProblem = true;
        }

        // 记录问题（每个单号只计一次失败）
        if (hasProblem) {
          stats.failed++;
        } else {
          // 有效订单加入更新队列
          validItemsToUpdate.push({
            ...item,
            orderStatus: 'MANUAL_SERVICE',
            content: `客服${user.nickName}整理上传匹配成功`,
            customer: user.id,
            buType: this.buType,
          });
        }
      }

      // 批量更新有效订单
      if (validItemsToUpdate.length > 0) {
        try {
          await updateOrderStatus(validItemsToUpdate);
          stats.success += validItemsToUpdate.length;
        } catch (e) {
          // 更新失败计入失败
          stats.failed += validItemsToUpdate.length;
          validItemsToUpdate.forEach(item => {
            const id = orderType === 0 ? item.tid : item.sid;
            this.recordProblem(stats, id, stats.PROBLEM_TYPES.UPDATE_FAILED);
          });
        }
      }

      this.finalizeResult(stats);
    },
    /** 最终结果处理 */
    finalizeResult(stats) {
      // 确保统计准确
      if (stats.success + stats.failed > stats.total) {
        stats.failed = stats.total - stats.success;
      }

      // 构建问题详情
      const problemDetails = [];

      // 收集所有问题单号，并按照原始单号顺序列出问题
      stats.uploadList.forEach(id => {
        if (stats.problemMap.has(id)) {
          const problems = stats.problemMap.get(id);
          problemDetails.push(`单号${id}：${problems.join('，')}`);
        }
      });

      // 构建结果日志
      let resultLog = `上传单号：${stats.uploadList.join(',')}，共${stats.total}条；`;
      resultLog += `成功：${stats.success}条；失败：${stats.failed}条；`;

      // 添加问题详情
      if (problemDetails.length > 0) {
        resultLog += `问题详情：${problemDetails.join('；')}`;
      }
      // 添加结果日志
      addCustomerLogs({content: resultLog})
      // 显示结果
      this.$alert(`成功：${stats.success}条；失败：${stats.failed}条；`, '处理结果', {
        confirmButtonText: '确定',
        callback: () => {
          this.$copyText(resultLog);
          this.$modal.msgSuccess('结果已复制到剪贴板');
          this.uploadVisible = false;
          this.getList();
        }
      });
    },
    /** 退回接收 */
    handleReceive(row){
      const ordersStatus = [{
        ...row,
        orderStatus: 'MANUAL_SERVICE',
        userId: null,
        deptId: null,
        accessTime: Date.now(),
        content: '设计师异常退回，客服已接收'
      }]

      updateOrderStatus(ordersStatus).then(res => {
        this.getList();
        this.$modal.msgSuccess("异常退回接收成功");
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取用户集合 */
    getUserList(){
      getNormalUserInfo().then(response => {
        this.userOptions = response.data;
        this.filteredUserOptions = [...this.userOptions];
      });
    },
    /** 部门改变获取用户集合 */
    handleUserList(value){
      if (value) {
        // 如果选择了部门，过滤出该部门的用户
        this.filteredUserOptions = this.userOptions.filter(item => item.deptId === value);
      } else {
        // 如果清空部门，恢复显示全部用户
        this.filteredUserOptions = [...this.userOptions];
      }
    },
    /** 查看客服整理日志 */
    handleViewCustomerLogs(){
      this.getCustomerLogsList();
      this.viewCustomerLogsVisible = true;

    },
    /** 获取客服整理日志 */
    getCustomerLogsList(){
      listCustomerLogs(this.$addDateRange(this.queryCustomerLogsParams, this.createTimeRange)).then(res => {
        this.customerLogsList = res.rows;
        this.customerTotal = res.total;
      })
    },
    /** 客服整理日志查询 */
    handleCustomerLogsQuery(){
      this.queryCustomerLogsParams.pageNum = 1;
      this.getCustomerLogsList();
    },
    /** 重置客服整理日志查询 */
    resetCustomerLogsQuery(){
      this.createTimeRange = [];
      this.$resetForm("queryCustomerLogsForm");
      this.handleCustomerLogsQuery();
    }
  }
};
</script>

<style scoped>
.custom-tooltip {
  max-width: 200px; /* 或者其他合适的宽度 */
  white-space: pre-line; /* 或者使用 pre，根据你的需求选择 */
}
.gift-text {
  color: red;
}

/* WebKit browsers (Chrome, Safari, Edge) */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

/* Firefox */
* {
  scrollbar-width: auto;
  scrollbar-color: #888 #f1f1f1;
}
</style>
